<template>
  <div class="uni-login-sign-wrap">
    <el-form class="uni-login-sign-form" :model="signForm" ref="signForm">
      <el-form-item>
        <el-input v-model="signForm.account"
                  @input="clearError"
                  :placeholder="$tt('EMAIL')"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="signForm.password"
                  @input="clearError"
                  :placeholder="$tt('PASSWORD')"
                  type="password"
                  show-password></el-input>
      </el-form-item>
      <el-form-item>
        <BaseCheckbox v-model="signForm.accept" uid="accept" @change="clearError">
          <label for="accept">{{ $tt("I've read and accepted the") }} </label>

          <a :href="endUserLicenseAgreement" target="_blank" class="uni-login-color-blue">{{
              $tt('User Agreement')
            }}</a>
          <span> {{ $tt('and') }} </span>
          <a :href="privacyPolicy" target="_blank" class="uni-login-color-blue">{{ $tt('Privacy Policy') }}</a>
        </BaseCheckbox>
      </el-form-item>
      <ErrorTips :error-map="errorMap" class="mb20"></ErrorTips>
      <div class="uni-login-btn"
           :class="{disabled: !canSign}"
           @click="canSign ? sign() : null">{{ $tt('Sign In') }}
      </div>
    </el-form>
    <OtherLogin :title="$tt('OR')" :before-go="checkAccept"></OtherLogin>
    <CanNotSignIn></CanNotSignIn>
  </div>
</template>

<script>
// import { isEmail } from '@/utils'
// import md5 from 'js-md5'
import {endUserLicenseAgreement, privacyPolicy} from '@/utils/links'

import getEnv from "@/utils/env";
import {loginWithAccount, refreshClientToken} from '@/api'
import BaseCheckbox from "@/componnets/BaseCheckbox";
import OtherLogin from "@/componnets/OtherLogin";
import ErrorTips from "@/componnets/ErrorTips";
import CanNotSignIn from "@/componnets/CanNotSignIn";
import {encryptPassWord} from "@/utils";

export default {
  components: {
    BaseCheckbox,
    ErrorTips,
    OtherLogin,
    CanNotSignIn
  },
  data() {
    return {
      endUserLicenseAgreement,
      privacyPolicy,
      getEnv,
      robotFlag: true,
      signForm: {
        account: '',
        password: '',
        type: 2, // 账号类型 0 账号 1手机号 2邮箱
        accept: false
      },
      signFormFlag: true, // 用来处理按是否可以点击
      errorMap: {
        tips: '',
        accept: ''
      },
      signLock: false
    }
  },
  computed: {
    canSign() {
      return this.signForm.account && this.signForm.password && this.signForm.accept
    }
  },
  methods: {
    async signIn(robotToken) {
      const params = JSON.parse(JSON.stringify(this.signForm))
      robotToken ? params.token = robotToken : null
      delete params.accept
      params.password = encryptPassWord(params.password)
      // 添加渠道信息
      this.$parent._addChannelInfo(params)
      const {code, data, msg} = await loginWithAccount(params)
      this.signLock = false
      if (code === 0) {
          if (this.$root.$options.props.app_key.type === 'A0002') {
              console.log(data.user_token, '---data.user_token----');
              const user = await refreshClientToken({
                  app_key: 'client'
              }, data.user_token);
              if (user.code === 0) {
                  console.log(this.$parent.loginSuccess);
                  this.$parent.loginSuccess(user.data);
              }
          } else {
              this.$parent.loginSuccess(data);
          }
      } else if (code === 430340) {
        this.errorMap.tips = this.$tt('You appear to be a robot, please retype again to try')
        this.signForm.account = ''
        this.signForm.password = ''
        this.signForm.accept = false
      } else if (code === 10000) { // 需人机验证
        this.robotFlag = true
        this.errorMap.tips = this.$tt('You appear to be a robot, please retype again to try')
        // this.signForm.account=''
        // this.signForm.password=''
        // this.signForm.accept=false


      } else if (code === 10016) { // 账号锁定1小时
        this.errorMap.tips = msg
      }
    },
    async sign() {
      const _this = this
      console.log(this.signLock)
      if (this.signLock) return
      this.signLock = true
      if (this.robotFlag) { // 目前先写死robotFlag=true 每次都进行人机验证（否则有一些逻辑判断问题。等待后期迭代）
        // eslint-disable-next-line no-undef
        grecaptcha.ready(function () {
          // eslint-disable-next-line no-undef
          grecaptcha.execute(process.env.VUE_APP_RECAPTCHA_ID, {action: 'submit'}).then((token) => {
            // Add your logic to submit to your backend server here.
            console.log(token)
            _this.signIn(token)
          }).catch((err) => {
            console.log(this);
            _this.signLock = false
            console.error(err)
          })
        })
      } else {
        await this.signIn()
      }
    },
    checkAccept() {
      if (!this.signForm.accept) {
        this.errorMap.accept = this.$tt("Please make sure you have read and accepted the User Agreement and Privacy Policy")
        return false
      } else {
        return true
      }
    },
    openLink(link) {
      window.open(link)
    },
    clearError() {
      this.errorMap.tips = ''
      this.errorMap.accept = ''
    }
  }
}
</script>
<style scoped lang="scss">
.uni-login-sign-wrap {
  padding-top: 30px;

  .divider {
    margin: 30px auto 0;
    width: 100px;
  }
}

.uni-login-btn {
  height: 50px;
  line-height: 50px;
  cursor: pointer;
  border-radius: 4px;
  background: linear-gradient(120deg, #aa1726, #dc2133);
  text-align: center;
  transition: .3s;
  margin-bottom: 30px;

  &:hover {
    filter: brightness(120%);
  }

  &.disabled {
    cursor: default;
    background: linear-gradient(120deg, #222, #1b1b1b);

    &:hover {
      filter: none;
    }
  }
}


.title-text {
  font-size: 40px;
  font-weight: 700;
  text-align: center;
  margin-bottom: 30px;
}

.sub-title-text {
  text-align: center;
  margin-bottom: 30px;
  font-size: 14px;
}

.login-wrap {
  ::v-deep(.el-form-item) {
    margin-bottom: 30px;
  }

  ::v-deep(.el-input__inner),
  ::v-deep(.el-input__inner) {
    height: 56px;
    line-height: 56px;
    border: none;
  }
}

</style>
